<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增模板')" />
    <th:block th:include="include :: codemirror-css"/>
	<th:block th:include="include :: jsonmate-css"/>
</head>
<body class="white-bg" th:object="${sysTemplate}">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-template-add" >
        <input name="templateId" th:field="*{templateId}" type="hidden">
        <div class="form-group">
            <label class="col-sm-3 control-label">模板名：</label>
            <div class="col-sm-8">
                <input name="mouldName" th:field="*{mouldName}" class="form-control" type="text">
            </div>
        </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">模板：</label>
                <div class="col-sm-8">
                    <div id="editContent">
                        <div class="btn-group" style="position: absolute; z-index: 1000;top:20px;right: 25px;">
                            <a class="btn btn-white btn-bitbucket" href="javascript:autoFormatSelection()" style="background-color: #3535356b;">
                                <i class="fa fa-align-justify" style="color: white"></i>
                            </a>
                            <a class="btn btn-white btn-bitbucket" id="fullScreen" style="background-color: #3535356b;">
                                <i class="fa fa-arrows-alt" style="color: white"></i>
                            </a>
                            <a class="btn btn-white btn-bitbucket"  id="eyeBtn" href="javascript:checkTemplate()" style="background-color: #3535356b;">
                                <i class="fa fa-eye" style="color: white"></i>
                            </a>
                        </div>
                        <textarea id="temCode" th:field="*{templateHtml}"  name="templateHtml">
                         </textarea>
                    </div>
                </div>
            </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">模板数据：</label>
            <div class="col-sm-8">
                <input name="templateData"  type="hidden">
                <div id="modelData" class="json-editor"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">模板状态：</label>
            <div class="col-sm-8">
                <div class="radio-box" th:each="dict : ${@dict.getType('sys_template_visible')}">
                    <input type="radio" th:id="${dict.dictCode}" name="visible" th:value="${dict.dictValue}" th:checked="${dict.default}">
                    <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">是否内置：</label>
            <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dict.getType('sys_template_built')}">
                        <input type="radio" th:id="${dict.dictCode}" name="built" th:value="${dict.dictValue}" th:checked="${dict.default}">
                        <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">模板用途：</label>
            <div class="col-sm-8">
                    <div class="radio-box" th:each="dict : ${@dict.getType('sys_template_used')}">
                        <input type="radio" th:id="${dict.dictCode}" name="templateUsed" th:value="${dict.dictValue}" th:checked="${dict.default}">
                        <label th:for="${dict.dictCode}" th:text="${dict.dictLabel}"></label>
                    </div>
            </div>
        </div>
        <a class="btn btn-success" onclick="submitHandler()">
            <i class="fa fa-plus"></i> 添加
        </a>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: codemirror-js"/>
    <th:block th:include="include :: fullscreen-js"/>
 <th:block th:include="include :: jsonmate-js"/>
    <script type="text/javascript" th:inline="javascript">
        var json=JSON.parse([[${sysTemplate.templateData}]]);
        //设置路径前缀
        var prefix = ctx + "system/template";

        //设置允许iframe全屏
        for (i = 0; i < window.top.document.getElementsByTagName("iframe").length; i++) {
            window.top.document.getElementsByTagName("iframe")[i].setAttribute("allowfullscreen",true);
        }

        //高亮折叠编辑器插件
        var  editor = CodeMirror.fromTextArea(document.getElementById("temCode"), {
            mode: "text/html",
            theme:"erlang-dark",
            lineNumbers: true,	//显示行号
            lineWrapping: true, //代码折叠
            foldGutter: true,
            gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
            matchBrackets: true,  //括号匹配
            extraKeys: {"Ctrl-Space": "autocomplete"}
        });
		//设置高亮编辑器高
        editor.setSize(null,"200px");

        //获取选择范围
        function getSelectedRange() {
            return { from: editor.getCursor(true), to: editor.getCursor(false) };
        }
        //格式化
        function autoFormatSelection() {
            var range = getSelectedRange();
            editor.autoFormatRange(range.from, range.to);
        }
        //注释
        function commentSelection(isComment) {
            var range = getSelectedRange();
            editor.commentRange(isComment, range.from, range.to);
        }

		function printJSON() {
		    $('#json').val(JSON.stringify(json));
		
		}
		function updateJSON(data) {
		    json = data;
		    printJSON();
		}
		function showPath(path) {
		    $('#path').text(path);
		}
		$(document).ready(function() {
		
		    $('#rest > button').click(function() {
		        var url = $('#rest-url').val();
		        $.ajax({
		            url: url,
		            dataType: 'jsonp',
		            jsonp: $('#rest-callback').val(),
		            success: function(data) {
		                json = data;
		                $('#modelData').jsonEditor(json, { change: updateJSON, propertyclick: showPath });
		                printJSON();
		            },
		            error: function() {
		                alert('Something went wrong, double-check the URL and callback parameter.');
		            }
		        });
		    });
		
		    $('#json').change(function() {
		        var val = $('#json').val();
		
		        if (val) {
		            try { json = JSON.parse(val); }
		            catch (e) { alert('Error in parsing json. ' + e); }
		        } else {
		            json = {};
		        }
		        
		        $('#modelData').jsonEditor(json, { change: updateJSON, propertyclick: showPath });
		    });
		
		    $('#expander').click(function() {
		        var editor = $('#editor');
		        editor.toggleClass('expanded');
		        $(this).text(editor.hasClass('expanded') ? 'Collapse' : 'Expand all');
		    });
		    
		    printJSON();
		    $('#modelData').jsonEditor(json, { change: updateJSON, propertyclick: showPath });
		});

        function tml(){
            console.log(editor.getValue());
        }
        //表单验证
        $("#form-template-add").validate({
            focusCleanup: true
        });

        //表单提交
        function submitHandler() {
          $("#temCode").text(editor.getValue());
          $("input[name='templateData']").val(JSON.stringify(json));
            if ($.validate.form()) {
             $.operate.saveTab(prefix + "/add", $("#form-template-add").serialize());
            }
        }
        var fuj=false;
        //编辑器全屏事件
        $("#fullScreen").click(function(e){
            if (!fuj)
            { $("#editContent").fullScreen(true);}
            else {$("#editContent").fullScreen(false);
            }
            layer.closeAll();
            e.preventDefault();
        });
        $(document).bind("fullscreenchange", function(e) {
            fuj=!fuj;
            $("#editContent").fullScreen(fuj);
            if(fuj)
            {
                $("#eyeBtn").hide();
                editor.setSize(null,"100vh");
            }
            else
            {
                $("#eyeBtn").show();
                editor.setSize(null,"200px");
            }
        });
        function checkTemplate(){
            $.post(prefix+"/checkTemplate",{"templateHtml":editor.getValue(),"templateData":JSON.stringify(json)},function(data,status){
                if(data.code===0)
                {
                    $.modal.openFullPage("模板展示",'<iframe id="preview" style="width: 100%;height: 100%;border: none"></iframe>');
                    function updatePreview() {
                        var previewFrame = document.getElementById('preview');
                        var preview =  previewFrame.contentDocument ||  previewFrame.contentWindow.document;
                        preview.open();
                        preview.write(editor.getValue());
                        preview.close();
                    }
                    updatePreview();
                }
                else {
                    $.modal.alertError(data.msg);
                }
            });
        }
    </script>
</body>
</html>